import 'dart:io';

import 'package:hrf_app/common/api/bug/bug.dart';
import 'package:hrf_app/common/models/bug/file_model.dart';
import 'package:hrf_app/common/models/bug/project_model.dart';
import 'package:hrf_app/common/models/bug/project_user_model.dart';
import 'package:hrf_app/common/routers/names.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:get/state_manager.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class ProjectBugAddPageController extends GetxController {
  ProjectBugAddPageController();

  TextEditingController titleController =  TextEditingController();
  TextEditingController assignUserController =  TextEditingController();
  TextEditingController contentController =  TextEditingController();
  TextEditingController projectController =  TextEditingController();
  TextEditingController priorityController =  TextEditingController();
  List<ProjectModel> projectModelList = [];
  List<ProjectUserModel> projectUserList = [];
  List<UploadFileModel> uploadFileModelList = [];
  Map saveMap = {};

  _initData() {
    getPjProjectUserList();
    getProjectList();
    update(["ProjectBugAddPage"]);
  }

  void onTap() {}

  // @override
  // void onInit() {
  //   super.onInit();
  // }

  getPjProjectUserList() async {
    List<ProjectUserModel> userList = [];
    Map<String, dynamic> res = await BugApi.getPjProjectUserListApi({});
    for (var item in res["data"]) {
      userList.add(ProjectUserModel.fromJson(item));
    }
    projectUserList = userList;
  }

  void getProjectList() {
    BugApi.getPjProjectByUserIdApi({"id": "1111"}).then((res) {
      if (res["code"] == "00000") {
        for (var item in res["data"]) {
          projectModelList.add(ProjectModel.fromJson(item));
        }
      }
    });
  }

  void selectPriorityListDialog(String content, String filedName,
      String title) async {
    List<dynamic> priorityList = [
      {"id": "1", "name": "低"},
      {"id": "2", "name": "中"},
      {"id": "3", "name": "高"},
    ];
    Picker picket = Picker(
        adapter: PickerDataAdapter<String>(
            pickerdata: priorityList.map((item) => item["name"]).toList()),
        hideHeader: true);
    BuildContext? buildContext = Get.context!;
    Navigator.of(buildContext).push(TDSlidePopupRoute(
        slideTransitionFrom: SlideTransitionFrom.bottom,
        builder: (buildContext) {
          return TDPopupBottomConfirmPanel(
              title: title,
              leftClick: () {
                Navigator.maybePop(buildContext);
              },
              rightClick: () {
                List<dynamic> value = picket.getSelectedValues();
                List<int> index = picket.selecteds;
                if (value.isEmpty) return;
                Map projectUserModel = priorityList[index[0]];
                priorityController.text = projectUserModel["name"]!;
                saveMap["priority"] = projectUserModel["id"];
                Navigator.maybePop(buildContext);
              },
              child: picket.makePicker());
        }));
  }

  void selectProjectListDialog(String content, String filedName,
      String title) async {
    Picker picket = Picker(
        adapter: PickerDataAdapter<String>(
            pickerdata: projectModelList.map((item) => item.name).toList()),
        hideHeader: true);
    BuildContext? buildContext = Get.context!;
    Navigator.of(buildContext).push(TDSlidePopupRoute(
        slideTransitionFrom: SlideTransitionFrom.bottom,
        builder: (buildContext) {
          return TDPopupBottomConfirmPanel(
              title: title,
              leftClick: () {
                Navigator.maybePop(buildContext);
              },
              rightClick: () {
                List<dynamic> value = picket.getSelectedValues();
                List<int> index = picket.selecteds;
                if (value.isEmpty) return;
                ProjectModel projectUserModel = projectModelList[index[0]];
                projectController.text = projectUserModel.name!;
                saveMap["projectId"] = projectUserModel.id;
                Navigator.maybePop(buildContext);
              },
              child: picket.makePicker());
        }));
  }

  void editAssignUserDialog(String content, String filedName,
      String title) async {
    Picker picket = Picker(
        adapter: PickerDataAdapter<String>(
            pickerdata: projectUserList.map((item) => item.realName).toList()),
        hideHeader: true);
    BuildContext? buildContext = Get.context!;
    Navigator.of(buildContext).push(TDSlidePopupRoute(
        slideTransitionFrom: SlideTransitionFrom.bottom,
        builder: (buildContext) {
          return TDPopupBottomConfirmPanel(
              title: title,
              leftClick: () {
                Navigator.maybePop(buildContext);
              },
              rightClick: () {
                List<dynamic> value = picket.getSelectedValues();
                List<int> index = picket.selecteds;
                if (value.isEmpty) return;
                ProjectUserModel projectUserModel = projectUserList[index[0]];
                assignUserController.text = projectUserModel.realName!;
                String userId = projectUserModel.userId!;
                saveMap["assignUserId"] = userId;
                Navigator.maybePop(buildContext);
              },
              child: picket.makePicker());
        }));
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  Future<void> selectPhoto(ImageSource source) async {
    List<File> images = [];
    final picker = ImagePicker();
    final XFile? pickedFile = await picker.pickImage(source: source);
    if (pickedFile != null) {
      images.add(File(pickedFile.path));
    }
    uploadImg(images);
  }

  Future<void> selectMultiImage() async {
    List<File> images = [];
    final picker = ImagePicker();
    final List<XFile> pickedFileList = await picker.pickMultiImage();
    List<File> imageList = [];
    if (pickedFileList != null) {
      imageList = pickedFileList.map((file) => File(file.path)).toList();
    }
    images.addAll(imageList);
    uploadImg(images);
  }

  Future<void> uploadImg(List<File> imgList) async {
    // 单个文件上传
    List<MultipartFile> multipartFile = [];
    for (var element in imgList) {
      // 压缩图片
      var result = await FlutterImageCompress.compressWithFile(
        element.absolute.path,
        quality: 50, // 压缩质量，0-100
      );
      // 将压缩后的图片保存到临时文件
      var compressedFile = File("${element.path}_compressed.jpg")
        ..writeAsBytesSync(result!);
      // 将压缩后的文件转换为 MultipartFile
        MultipartFile mfile = await MultipartFile.fromFile(
          compressedFile.path,
        );
        multipartFile.add(mfile);
      }

      FormData formData = FormData.fromMap({'fileList': multipartFile});

      BugApi.simpleUploadListApi(formData).then((res) {
        if (res["code"] == "00000") {
          List<dynamic> imgUrlMap = res['data'];
          for (var itemVo in imgUrlMap) {
            UploadFileModel uploadFileModel = UploadFileModel();
            uploadFileModel.url = "/" + itemVo;
            uploadFileModelList.add(uploadFileModel);
          }
          TDToast.showSuccess("上传成功", context: Get.context!);
          update(["ProjectBugAddPage"]);
        }
      });
    }

    save() {
      String content = contentController.text;
      String title = titleController.text;
      String project = projectController.text;
      String priority = priorityController.text;
      String assign = assignUserController.text;
      saveMap['content'] = content;
      saveMap['title'] = title;
      saveMap['pjProjectBugFileVoList'] = uploadFileModelList;
      print(saveMap.toString());

      BugApi.addPjProjectBugApi(saveMap).then((res) {
        if (res["code"] == "00000") {
          Get.toNamed(RouteNames.projectBugPage);
        }
      });
    }

    void delImage(index) {
      if (index >= 0 && index < uploadFileModelList.length) {
        uploadFileModelList.removeAt(index);
        update(["ProjectBugAddPage"]);
      }
    }

// @override
// void onClose() {
//   super.onClose();
// }
  }
